<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>LayIM测试</title>
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>
<ul class="layui-nav layui-bg-green layui-anim layui-anim-scaleSpring" lay-filter="">
    <li class="layui-nav-item">
        <a href="logout"><i class="layui-icon">&#xe66b;</i> 退出</a>
    </li>
</ul>
<script src="../layui/layui.js"></script>
<script src="../layui/ajax.js"></script>
<script>
    layui.use(['layim','jquery'], function(layim){

        var storage = window.localStorage;

        var usernumber = storage.getItem("usernumber");

        //设置layim对象
        var layim = layui.layim;
        //声明jquery
        var $ = layui.jquery;
        //第一次（或重连）初始化连接
        var CONNECT = 1;
        //聊天消息
        var CHAT = 2;
        //消息签收
        var SIGNED = 3;
        //客户端保持心跳
        var KEEPALIVE = 4;
        //设置全局websocket
        var websocket = null;

        //判断当前浏览器是否支持WebSocket
        if('WebSocket' in window){
            //这里我用的是nginx+域名访问的，所以采用wss连接方式
            websocket = new WebSocket("ws://localhost:8088/ws");
        }
        else{
            alert('您的浏览器不支持websocker')
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function(){
            websocket.close();
        };

        //连接成功建立的回调方法
        websocket.onopen = function(event){
            //传入1
            var mineObj = new Object();
            mineObj.action = CONNECT;
            mineObj.usernumber = usernumber;
            //mian对象
            var obj = new Object();
            obj.mine = mineObj;
            websocket.send(JSON.stringify(obj));
        };

        //接收消息
        websocket.onmessage = function(event){

            var content = JSON.parse(event.data);

            console.log(content);

            /**=============用户离线的消息，消息将重新发送==========**/
            var mineObj = new Object();
            mineObj.action = SIGNED;
            mineObj.extand = content.msgId;
            //mian对象
            var obj = new Object();
            obj.mine = mineObj;
            websocket.send((JSON.stringify(obj)));
            /**=============消息签收结束==========**/

            /**==============开始展示消息接收到的消息==========**/
            var objMsg = new Object();
            objMsg.username = content.mine.username;
            objMsg.avatar = content.mine.avatar;
            objMsg.type = content.type;
            objMsg.content = content.mine.content;
            objMsg.fromid = content.mine.fromid;
            objMsg.timestamp = content.mine.timestamp;
            if(content.type == "friend"){
                //单聊
                objMsg.id = content.mine.id;
                objMsg.mine = false;
            }else{
                //群聊
                objMsg.id = content.to.id;
                objMsg.mine = false;
            }
            layim.getMessage(objMsg);
            /**==============结束展示消息接收到的消息==========**/

        };

        //关闭websocket
        websocket.onclose = function(){
            websocket.close();
        };

        //websocket发生错误
        websocket.onerror = function(){
            layim.getMessage("连接错误");
        };

        //配置聊天面板
        layim.config({
            init: {
                url: '../mine/getInit' //接口地址（返回的数据格式见下文）
                ,type: 'get' //默认get，一般可不填
                ,data: {} //额外参数
            }
            ,members: {
                url: "../mine/getMineGrouping"
                ,data: {}
            }
            ,title:"我的IMZZ"
            ,notice: true //是否开启桌面消息提醒，默认false
            ,msgbox: '../layim/demo/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
            ,find: "../../mine/getMineList"
            ,chatLog: '../layim/demo/chatlog.html' //聊天记录页面地址，若不开启，剔除该项即可
        });

        //监听发送消息
        layim.on('sendMessage', function(data){
            var mine = data.mine;
            mine.action = CHAT;
            websocket.send((JSON.stringify(data)));
        });

        //修改在线状态
        layim.on('online', function(status){
            var mine = new Object();
            mine.usernumber = usernumber;
            mine.status = status;
            dataAjax($,"../mine/updateMine",mine,function(result){
                if(result.code == 0)
                    layer.msg(result.data);
                else{
                    layer.msg(result.msg);
                }
            });
        });

        //修改个性签名
        layim.on('sign', function(value){
            var mine = new Object();
            mine.usernumber = usernumber;
            mine.sign = value;
            dataAjax($,"../mine/updateMine",mine,function(result){
                if(result.code == 0)
                    layer.msg(result.data);
                else{
                    layer.msg(result.msg);
                }
            });
        });
    });
</script>
</body>
</html>